<template>
  <div class="delivery_management">
    <div class="search-box">
      <Row type="flex">
        <Row type="flex"
             justify="start"
             class="search-item-left">
          <Col class="search-item">
          <span class="search-label">输入搜索：</span>
          <Input placeholder="标准名称/PN"
                 style="width:180px"
                 v-model='searchObj.pnCodeOrName'></Input></Col>
          <Col class="search-item">
          <span class="search-label">发货类型：</span>
          <Select v-model="searchObj.shippingType"
                  :clearable="clearable"
                  @on-change="seleted"
                  style="width:180px"
                  placeholder='请选择'>
            <Option v-for="item in typeList"
                    :value="item.id"
                    :key="item.id">{{ item.value }}</Option>
          </Select>
          </Col>
          <Col class="search-item">
          <span class="search-label">收货状态:</span>
          <Select v-model="searchObj.invoiceStatus"
                  @on-change="seleted"
                  clearable
                  placeholder="请选择">
            <Option value=0>未收货</Option>
            <Option value=1>已收货</Option>
            <Option value=2>已终止</Option>
          </Select>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  type='primary'
                  @click="seleted">查询</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  @click="reset">重置</Button>
          </Col>
        </Row>
        <Row type="flex"
             justify="end"
             class="search-item-right">
          <Col class="search-item">
          <Button v-if="exampleShow"
                  @click="exampleOpen">收起筛选
            <Icon type="ios-arrow-up" />
          </Button>
          <Button v-else
                  @click="exampleOpen">更多筛选
            <Icon type="ios-arrow-down" />
          </Button>
          </Col>
        </Row>
      </Row>
      <div class="search-example"
           v-show="!exampleShow">
        <Row type="flex">
          <Row type="flex"
               justify="start"
               class="search-item-left">
          </Row>
          <Row type="flex"
               justify="end"
               class="search-item-right search-item-right01">
            <Col class="search-item">
            <Dropdown trigger="click"
                      @on-click="seletType"
                      v-if="hasPermission('moms:assets:invoiceimport')">
              <Button>导入
                <Icon type="ios-arrow-down" />
              </Button>
              <DropdownMenu slot="list">
                <DropdownItem name="1">采购订单</DropdownItem>
                <DropdownItem name="2">调拨单</DropdownItem>
                <DropdownItem name="3">处置单</DropdownItem>
              </DropdownMenu>
            </Dropdown>
            <Dropdown trigger="click"
                      style="margin-left:20px;"
                      v-if="hasPermission('moms:assets:invoicepurchase')||hasPermission('moms:assets:invoicecooperate')||hasPermission('moms:assets:invoicetrial')"
                      @on-click="add">
              <Button>新增发货
                <Icon type="ios-arrow-down" />
              </Button>
              <DropdownMenu slot="list">
                <DropdownItem name="1"
                              v-if="hasPermission('moms:assets:invoicepurchase')">新购</DropdownItem>
                <DropdownItem name="2"
                              v-if="hasPermission('moms:assets:invoicecooperate')">合作</DropdownItem>
                <DropdownItem name="3"
                              v-if="hasPermission('moms:assets:invoicetrial')">试用</DropdownItem>
              </DropdownMenu>
            </Dropdown>
            </Col>
          </Row>
        </Row>
      </div>
      <div class="search-example"
           v-show="exampleShow">
        <Row type="flex">
          <Row type="flex"
               justify="start"
               class="search-item-left">
            <Col class="search-item">
            <span class="search-label"
                  style="line-height:36px;display:inline-block;vertical-align: top;
">门店名称：</span>
            <div style="display:inline-block">
              <vueTreeselectChoice :multiple="true"
                                   ref="vueTreeselectChoice"
                                   @input="handleShop"
                                   @on-api-finish="apiFinish"
                                   permissionCode="moms:assets:invoiceview"
                                   v-model="searchObj.shopIds"></vueTreeselectChoice>
            </div>
            </Col>
            <Col class="search-item">
            <span class="search-label">发货时间：</span>
            <!-- <DatePicker type="daterange"
                        v-model="createTime"
                        @on-change="seleted"
                        style="width:180px;"
                        class="search-picker"></DatePicker> -->
            <datePickerYmd @on-change="seleted"
                           :selectDateType.sync='selectDateType02'
                           :dataType='dataType02'
                           :dateOption="dateOption"
                           clearable
                           v-model="timeDate02"
                           style="display:inline-block"></datePickerYmd>
            </Col>
            <Col class="search-item">
            <span class="search-label">收货时间:</span>
            <!-- <DatePicker type="daterange"
                        style="width:180px;"
                        @on-change="seleted"
                        v-model="finishTime"
                        class="search-picker"></DatePicker> -->
            <datePickerYmd @on-change="seleted"
                           :selectDateType.sync='selectDateType'
                           :dataType='dataType'
                           :dateOption="dateOption"
                           clearable
                           v-model="finishTime"
                           style="display:inline-block"></datePickerYmd>
            </Col>
          </Row>
          <Row type="flex"
               justify="end"
               class="search-item-right search-item-right01">
            <Col class="search-item">
            <Dropdown trigger="click"
                      @on-click="seletType"
                      v-if="hasPermission('moms:assets:invoiceimport')">
              <Button>导入
                <Icon type="ios-arrow-down" />
              </Button>
              <DropdownMenu slot="list">
                <DropdownItem name="1">采购订单</DropdownItem>
                <DropdownItem name="2">调拨单</DropdownItem>
                <DropdownItem name="3">处置单</DropdownItem>
              </DropdownMenu>
            </Dropdown>
            <Dropdown trigger="click"
                      style="margin-left:20px;"
                      v-if="hasPermission('moms:assets:invoicepurchase')|hasPermission('moms:assets:invoicecooperate')|hasPermission('moms:assets:invoicetrial')"
                      @on-click="add">
              <Button>新增发货
                <Icon type="ios-arrow-down" />
              </Button>
              <DropdownMenu slot="list">
                <DropdownItem name="1"
                              v-if="hasPermission('moms:assets:invoicepurchase')">新购</DropdownItem>
                <DropdownItem name="2"
                              v-if="hasPermission('moms:assets:invoicecooperate')">合作</DropdownItem>
                <DropdownItem name="3"
                              v-if="hasPermission('moms:assets:invoicetrial')">试用</DropdownItem>
              </DropdownMenu>
            </Dropdown>
            </Col>
          </Row>
        </Row>
      </div>
    </div>
    <Table stripe
           class="table-list"
           :columns="columns"
           :data="tableData"
           :loading="loading"
           :height="tableHeight">
      <template slot-scope="{ row,index }"
                slot="serial">
        <span>{{index+1}}</span>
      </template>
      <template slot-scope="{ row }"
                slot="shippingType">
        <span>{{['','新购','合作','试用','调拨'][row.shippingType]}}</span>
      </template>
      <template slot-scope="{ row }"
                slot="invoiceStatus">
        <span>{{['未收货','已收货','已终止'][row.invoiceStatus]}}</span>
      </template>
      <template slot-scope="{ row }"
                slot="action">
        <i class="iconsys icondetail"
           title="查看"
           v-if="hasPermission('moms:assets:invoicedetail')"
           @click="lookDetail(row.invoiceId)"></i>
        <Poptip confirm
                title="你确定要中止吗？"
                @on-ok="ok(row)"
                v-if="hasPermission('moms:assets:invoiceclose')&&row.invoiceStatus===0"
                @on-cancel="cancel">
          <i class="iconsys icontingyong"
             title="中止"></i>
        </Poptip>
      </template>
    </Table>
    <Row type='flex'
         justify="end"
         style='padding: 20px'>
      <Col>
      <Page :total="pageObj.total"
            :page-size='pageObj.pageSize'
            :current='pageObj.pageIndex'
            :page-size-opts='[10,20,30,40]'
            show-total
            show-sizer
            @on-change='changePageIndex'
            @on-page-size-change='changePageSize' />
      </Col>
    </Row>
  </div>
</template>
<script>
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
import { invoiceList, invoiceClose } from '@/api/asset/repair/asset-manage.js'
import datePickerYmd from '@/components/date-picker-ymd/date-picker-ymd.vue'
import { getOrgAllTree } from '@/api/system/org'
import dayjs from 'dayjs'
export default {
  name: 'delivery_management',
  components: { vueTreeselectChoice, datePickerYmd },
  data () {
    return {
      clearable: true,
      typeList: [
        { id: 1, value: '新购' },
        { id: 2, value: '合作' },
        { id: 3, value: '试用' }
      ],
      exampleShow: false,
      tableData: [],
      createTime: ['', ''],
      options: [],
      shopIdArr: [],
      dateOption: {
        disabledDate: date => {
          if (process.env.NODE_BUILD === 'prod') return dayjs(date).isAfter(dayjs(new Date()).subtract(1, 'day'))
          return dayjs(date).isAfter(dayjs(new Date()))
        }
      },
      dataType: [{ key: 'month', value: '月' }, { key: 'daterange', value: '自定义' }],
      finishTime: [dayjs().subtract(1, 'day').format('YYYY-MM-DD 00:00:00'), dayjs(new Date()).format('YYYY-MM-DD 00:00:00')],
      selectDateType: '',
      selectDateType02: '',
      dataType02: [{ key: 'month', value: '月' }, { key: 'daterange', value: '自定义' }],
      timeDate02: [dayjs().subtract(1, 'day').format('YYYY-MM-DD 00:00:00'), dayjs(new Date()).format('YYYY-MM-DD 00:00:00')],
      columns: [
        {
          title: '序号',
          slot: 'serial',
          width: 100
        },
        {
          title: '发货类型',
          slot: 'shippingType'
        },
        {
          title: '标准名称',
          key: 'name',
          width: 150
        },
        {
          title: '供应商简称',
          key: 'supplyName'
        },
        {
          title: '发货人',
          key: 'consignorName'
        },
        {
          title: 'PN',
          key: 'pnCode',
          width: 150
        },
        {
          title: '发货门店',
          key: 'shopName'
        },
        {
          title: '发货数量',
          key: 'shippedQuantity',
          width: 100
        },
        {
          title: '发货日期',
          key: 'createTime',
          width: 150
        },
        {
          title: '收货状态',
          slot: 'invoiceStatus'
        },
        {
          title: '收货时间',
          key: 'finishTime',
          width: 150
        }
        // {
        //   title: '操作',
        //   slot: 'action',
        //   width: 200
        // }
      ],
      loading: false,
      searchObj: {
        pnCodeOrName: '',
        shippingType: '',
        invoiceStatus: '',
        shopIds: []
      },
      pageObj: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      }
    }
  },
  watch: {
    '$route' (newRoute) {
      if (newRoute.name === 'delivery_management') {
        this.getlist()
      }
    }
  },
  created () {
    this.getOrg()
    if (this.hasPermission(['moms:assets:invoicedetail', 'moms:assets:invoiceclose'])) {
      this.columns.push({
        title: '操作',
        width: 180,
        slot: 'action'
      })
    }
  },
  computed: {
    tableHeight () {
      let height = this.tableData.length > 10 ? 580 : 0
      return height
    },
    finishTimeStart () {
      if (this.finishTime[0] === 'Invalid Date') return ''
      return this.finishTime[0]
    },
    finishTimeEnd () {
      if (this.finishTime[1] === 'Invalid Date') return ''
      if (this.selectDateType === 'daterange') return dayjs(this.finishTime[1]).add(1, 'day').format('YYYY-MM-DD 00:00:00')
      return this.finishTime[1]
    },
    createTimeStart () {
      if (this.timeDate02[0] === 'Invalid Date') return ''
      return this.timeDate02[0]
    },
    createTimeEnd () {
      if (this.timeDate02[1] === 'Invalid Date') return ''
      if (this.selectDateType02 === 'daterange') return dayjs(this.timeDate02[1]).add(1, 'day').format('YYYY-MM-DD 00:00:00')
      return this.timeDate02[1]
    }
  },
  methods: {
    seleted () {
      this.pageObj.pageIndex = 1
      this.getlist()
    },
    getOrg () {
      getOrgAllTree({
        'merchantId': this.$store.state.user.merchantId,
        'orgType': 1,
        status: 1,
        perms: 'moms:assets:invoiceview'
      }).then(res => {
        if (res.data.status === 200) {
          this.options = [res.data.data]
          this.shopIdArr = []
          this.filterData(this.options)
          if (this.shopIdArr.length) {
            this.getlist()
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    filterData (data) {
      if (data) {
        data.forEach(ele => {
          if (ele.orgType === 1) {
            if (this.shopIdArr.indexOf(ele.id) < 0) {
              this.shopIdArr.push(ele.id)
            }
          } else {
            this.filterData(ele.childList)
          }
        })
      }
    },
    add (type) {
      this.$router.push({ name: 'delivery_create', query: { type: type } })
    },
    seletType (type) {
      this.$router.push({ name: 'delivery_import', query: { type: type } })
    },
    ok (row) {
      invoiceClose({
        invoiceId: row.invoiceId
      }).then(res => {
        if (res.data.status === 200) {
          this.$Message.success('成功中止')
          this.getlist()
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    cancel () {

    },
    reset () {
      this.searchObj = {
        pnCodeOrName: '',
        shippingType: '',
        invoiceStatus: '',
        shopIds: []
      }
      this.selectDateType02 = ''
      this.selectDateType = ''
      this.pageObj.pageIndex = 1
      this.pageObj.pageSize = 10
      this.getlist()
    },
    async handleShop () {
      const ids = await this.$refs.vueTreeselectChoice.getShopId()
      this.searchObj.shopIds = ids
      this.seleted()
    },
    skipAdd () {

    },
    getlist () {
      if (this.shopIdArr.length) {
        this.loading = true
        invoiceList({
          ...this.searchObj,
          shopIds: this.searchObj.shopIds.length ? this.searchObj.shopIds : this.shopIdArr,
          offset: (this.pageObj.pageIndex - 1) * this.pageObj.pageSize,
          limit: this.pageObj.pageSize,
          merchantId: this.$store.state.user.merchantId,
          createTimeStart: this.selectDateType02 ? this.createTimeStart : '',
          createTimeEnd: this.selectDateType02 ? this.createTimeEnd : '',
          finishTimeStart: this.selectDateType ? this.finishTimeStart : '',
          finishTimeEnd: this.selectDateType ? this.finishTimeEnd : ''
        }).then(res => {
          this.loading = false
          if (res.data.status === 200) {
            this.pageObj.total = res.data.totalCount
            this.tableData = res.data.data || []
          } else {
            this.$Message.error(`${res.data.error}`)
          }
        })
      }
    },
    changePageIndex (pageIndex) {
      this.pageObj.pageIndex = pageIndex
      this.getlist()
    },
    lookDetail (id) {
      console.log(id)
      this.$router.push({ name: 'delivery_detail', query: { invoiceId: id } })
    },
    changePageSize (pageSize) {
      this.pageObj.pageSize = pageSize
      this.getlist()
    },
    apiFinish () {
      this.ShopValue = null
    },
    // 筛选按钮
    exampleOpen () {
      this.exampleShow = !this.exampleShow
    }
  }
}
</script>
<style lang="less" scoped>
.delivery_management {
  .search-example {
    width: 100%;
    .search-item-left {
      width: ~'calc(100% - 250px)';
    }
    .search-item-right {
      width: 250px;
    }
  }
  .search-items {
    margin-left: 30px;
    padding-top: 24px;
  }
}
</style>
<style>
.delivery_management .search-item .ivu-input-wrapper {
  /* width: 300px; */
}
</style>
